package com.smart4j.framework.helper;

import com.smart4j.framework.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * bean助手类
 *
 * @author 段誉
 * @create 2019-04-01 16:06
 */
public final class BeanHelper {
  /**
   * 定义Bean映射（用于存放Bean类与Bean实例的映射关系）
   */
  private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>();

  static {
    //获取所有的bean类
    Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
    //根据类实例化对象
    beanClassSet.forEach(bc ->  BEAN_MAP.put(bc, ReflectionUtil.newInstance(bc)));
  }

  /**
   * 获取Bean映射
   */
  public static Map<Class<?>, Object> getBeanMap() {
    return BEAN_MAP;
  }

  /**
   * 获取Bean实例
   */
  @SuppressWarnings("unchecked")
  public static <T> T getBean(Class<T> cls) {
    if (!BEAN_MAP.containsKey(cls)) {
      throw new RuntimeException("cant not get bean by class:" + cls);
    }
    return (T) BEAN_MAP.get(cls);
  }
}
